<template>
  <el-card v-if="permission"
           v-loading="fields_loading"
           shadow="never"
           class="aui-card--fill datasetview absolute inset-0 flex flex-col">
    <div style="display: flex;justify-content: space-between;align-items: center;padding: 0 20px;height: 48px;box-shadow: 0px 0px 8px 0px #F0F0F0;border-radius: 4px;border: 1px solid rgba(0, 0, 0, 0.01);">
      <div style="display: flex;align-items: center;font-size: 20px;font-weight: 600;color: rgba(0, 0, 0, 0.75);">
        <img :src="$ossLink+'/app/mspbots_theme_icon/dataset.png'"
             alt=""
             style="width: 20px;height: 20px;margin-right: 10px;">
        <span>{{FieldsList.name}}</span>
        <div>
          <view-linked-info :linkKey="'Datasets-view-'+FieldsList.id"></view-linked-info>
        </div>
      </div>
      <div>
        <!-- <BCreateWidget :defaultDataset="FieldsList" /> -->

        <el-tooltip :open-delay="1000"
                    class="item"
                    effect="dark"
                    :content="$t('statement.sd')"
                    placement="top">
          <i class="cuifont icon_arrow_sync sync-dataset--icon cursor-pointer"
             @click="handleOpenRecentDialog('start')"></i>
        </el-tooltip>

     
        <el-tooltip :open-delay="1000"
                    class="item"
                    effect="dark"
                    content="Edit"
                    placement="top">
          <i class="cuifont icon_edit"
             style="margin-right:25px;font-size:14px;cursor: pointer;"
             v-if="hasEditPermission(FieldsList,'dataset')"
             @click="editDataset"></i>
        </el-tooltip>
        <el-tooltip :open-delay="1000"
                    class="item"
                    effect="dark"
                    content="Delete"
                    placement="top">
          <i class="cuifont icon_delete"
             v-if="hasDeletePermission(FieldsList,'dataset')"
             style="font-size:14px;cursor: pointer;"
             @click="deleteDataset"></i>
        </el-tooltip>
      </div>
    </div>
    <div style="height:10px;background-color:#f1f4f5;border-radius:2px;"></div>
    <div class="control-section"
         style="margin: 10px 10px;">
      <div class="content-wrapper">
        <el-tabs v-model="activeName"
                 @tab-click="handleClick"
                 style="">
          <el-tab-pane label="Detail"
                       name="Detail"
                       class="dataset_detail">
            <div class="cardHeader"
                 style="margin-top:0">
              <span class="cardTitle threepoints">{{$t('statement.datt')}}</span>
            </div>
            <p>{{$t('statement.dn')}}</p>
            <div>{{FieldsList.name}}</div>
            <p>{{$t('attribute.description')}}</p>
            <div>{{FieldsList.description}}</div>
            <p>{{$t('statement.lut')}}</p>
            <div>{{FieldsList.updateDate | ClientFormatTimer}}</div>
            <div style="">
              <div>
                <span class="cardTitle threepoints">{{$t('statement.rdch')}}</span>
              </div>
              <div v-loading="logLoading">
                <el-table :data="logList"
                          class="data-table-css screen-y scroll-css"
                          style="width:50%;font-size: 14px;"
                          :height="300">
                  <el-table-column prop="action"
                                   :label="$t('attribute.api')"
                                   align="left">
                    <!-- <template slot-scope="scope">
                      <el-button type="text"
                                 style="color:#138dc7"
                                 @click="handleOpenRecentDialog('view',scope.row)">{{scope.row.refreshName}}</el-button>
                    </template> -->
                  </el-table-column>
                  <el-table-column prop="type"
                                   :label="$t('attribute.type')"
                                   align="left">
                    <template slot-scope="scope">
                      {{scope.row.id | filterType}}
                    </template>
                  </el-table-column>

                  <el-table-column prop="createDate"
                                   label="Start"
                                   :width="170"
                                   align="left">
                    <template slot-scope="scope">
                      {{ scope.row.createDate | ClientFormatTimer }}
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="duration"
                                   label="Duration (s)"
                                   align="center"></el-table-column> -->
                  <el-table-column prop="status"
                                   label="Status"
                                   align="center">
                    <template slot-scope="scope">
                      <template v-if="scope.row.status !== 200"
                                :open-delay="1000">
                        <el-tooltip :content="scope.row.message"
                                    placement="top">
                          <el-tag size="mini"
                                  type="danger">Failed</el-tag>
                        </el-tooltip>
                      </template>
                      <el-tag v-else-if="scope.row.status"
                              size="mini"
                              type="success">Succeeded</el-tag>
                    </template>
                  </el-table-column>
                </el-table>

              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="Data"
                       name="datasets"
                       v-loading="loading">
            <div style="display:flex;flex-direction: column;">
              <div class="cardHeader">
              <div>
                  <i class="cardTitle threepoints"
                      style="width:300px;">Data Grid view</i>
                <i style="margin-left:10px">
                  <el-button-group>
                    <el-button size="mini"
                               title="Grid View"
                               @click="showGrid=true"
                               icon="el-icon-notebook-2"></el-button>
                    <el-button size="mini"
                               title="Pivot View"
                               @click="showGrid=false"
                               icon="el-icon-film"></el-button>
                  </el-button-group>
                </i>
              </div>
                <div style="display:flex;">
                      <div style="display: flex;justify-content: flex-end;width:300px;">
                  <el-radio-group v-model="rowLimitType">
                    <div>
                      <el-radio style="text-align:left;margin-top:0px"
                                :label="2"
                                @change="changeRowLimit"><span style="color:#404040">First </span>
                        <el-input v-model="rowLimit"
                                  style="width:88px"
                                  @change="changeRowLimit"
                                  @blur="blurRowLimit(dataSort)"
                                  placeholder="Pick a limit"></el-input><span style="color:#404040"> Row</span>
                      </el-radio>
                    </div>
                  </el-radio-group>
                </div>
                <div style="margin-left:30px">
                  <el-button @click="changeLayerStatus"
                             v-if="useLayerStatus"
                             class="cuifont icon_dataset_add_layer"
                             type="mini"
                             style="font-size:14px;padding:7px"></el-button>
                  <el-select v-if="!useLayerStatus"
                             v-loading='datasetLayerSelectLoading'
                             v-model="datasetLayerId"
                             @change="onLayerChange"
                             placeholder="Please Select Layer"
                             clearable
                             style="height:30px;">
                    <el-option v-for="(item,index) in layerTempList"
                               :label="item.name"
                               :key="index"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </div>
                <div style="margin-left:30px">
                  <div slot="reference"
                       class="default_sort cursor_pointer"
                       @click="openFilterDialog">
                    <span class="cuifont icon_filter"></span>
                    <span style="margin:0 8px">Filter</span>
                  </div>
                </div>
                <el-dialog :title="$t('custom.component.columns.filterSettings')"
                           :visible.sync="dialogVisible"
                           width="69rem"
                           :close-on-click-modal="false"
                           append-to-body
                           v-if="dialogVisible"
                           :before-close="handleClose">
                  <div v-loading="saveDatasetFilterLoading">
                    <TypeFilter :dataForm='filterSetting.dataForm'
                                :originDataId='FieldsList.id'
                                :originDataType='`dataset`'
                                :scriptItem='filterSetting.scriptItem'
                                ref="typeFilter"></TypeFilter>
                    <div slot="footer"
                         style="margin-top:10px;display:flex;justify-content: flex-end;"
                         class="dialog-footer">
                      <el-button @click="handleClose">cancel</el-button>
                      <el-button type="primary"
                                 @click="saveFilters(filterSetting.dataForm)">ok</el-button>
                    </div>
                  </div>
                </el-dialog>
                <div style="width:230px;">
                  <el-popover placement="bottom"
                              ref="sortPopver"
                              width="200"
                              @show="showDataSortDialog"
                              trigger="click"
                              popper-class="datset_filter"
                              style="display: flex;justify-content: flex-end;">
                    <div>
                      <!-- <div style="padding:8px">
                      <div style="color:#C0C0C0;font-size:12px;height:24px;margin-bottom:5px">Show</div>
                      <el-radio-group v-model="rowLimitType">
                        <div> -->
                      <!-- <el-radio :label="1"
                                    @change="changeRowLimit"><span style="color:#404040">All Row</span></el-radio> -->
                      <!-- <el-radio style="text-align:left;margin-top:0px"
                                    :label="2"
                                    @change="changeRowLimit"><span style="color:#404040">First </span>
                            <el-input v-model="rowLimit"
                                      style="width:88px"
                                      @change="changeRowLimit"
                                      placeholder="Pick a limit"></el-input><span style="color:#404040"> Row</span>
                          </el-radio>
                        </div>
                      </el-radio-group>
                    </div> -->
                      <div style="box-shadow: 0px -1px 0px 0px #F0F0F0;padding:8px">
                        <div style="color:#C0C0C0;font-size:12px;height:24px;margin-bottom:5px">Sort by</div>
                        <el-select v-model="dataSort.orderFields"
                                   placeholder="Please Select"
                                   filterable
                                   clearable>
                          <el-option v-for="item in filterSetting.scriptItem[this.filterSetting.scriptItem.keyOptions]"
                                     :key="item.value"
                                     :label="item.label"
                                     :value="item.value">
                          </el-option>
                        </el-select>
                      </div>
                      <div style="box-shadow: 0px -1px 0px 0px #F0F0F0;padding:8px;margin-bottom:5px">
                        <div style="color:#C0C0C0;font-size:12px;height:24px;margin-bottom:5px">From</div>
                        <div>
                          <div class="cursor_pointer"
                               :class="dataSort.orderBy === 'asc'?'active_from':''"
                               @click="dataSort.orderBy='asc'">
                            <span style="font-size:14px"
                                  class="cuifont icon_arrow_ascending"></span>
                            <span style="font-size:14px;margin-left:3px">Ascending</span>
                            <span v-if="dataSort.orderBy === 'asc'"
                                  class="cuifont icon_checkmark"
                                  style="font-size:8px;float:right"></span>
                          </div>
                          <div class="cursor_pointer"
                               :class="dataSort.orderBy === 'desc'?'active_from':''"
                               style="margin-top:10px"
                               @click="dataSort.orderBy='desc'">
                            <span style="font-size:14px"
                                  class="cuifont icon_arrow_descending"></span>
                            <span style="font-size:14px;margin-left:3px">Descending</span>
                            <span v-if="dataSort.orderBy === 'desc'"
                                  class="cuifont icon_checkmark"
                                  style="font-size:8px;float:right"></span>
                          </div>
                        </div>
                      </div>
                      <div style="box-shadow: 0px -1px 0px 0px #F0F0F0;padding:8px;text-align: right;">
                        <el-button size="mini"
                                   @click="handleClearSort"
                                   :loading="clearloading"
                                   :disabled="saveloading">Clear</el-button>
                        <el-button type="primary"
                                   size="mini"
                                   @click="changeLimit(dataSort,'save')"
                                   :loading="saveloading"
                                   :disabled="clearloading">Save</el-button>
                      </div>
                    </div>
                    <div slot="reference"
                         class="default_sort cursor_pointer">
                      <span class="cuifont icon_arrow_sort"></span>
                      <span style="margin:0 8px">Default Sort</span>
                      <span style="font-size:8px"
                            class="cuifont icon_chevron_down"></span>
                    </div>
                  </el-popover>
                </div>
                </div>
              </div>
              <ejs-grid v-if="comDataList&&comDataList.length>0&&showGrid"
                        :dataSource="comDataList"
                        :allowResizing="gadgetSetting.report.allowResizing"
                        :allowFiltering="gadgetSetting.report.allowFiltering"
                        :filterSettings="gadgetSetting.report.filterSettings"
                        :allowGrouping="gadgetSetting.report.allowGrouping"
                        :allowPaging="gadgetSetting.report.allowPaging"
                        :toolbar="gadgetSetting.report.toolbar"
                        :allowTextWrap="gadgetSetting.report.allowTextWrap"
                        :showColumnChooser="gadgetSetting.report.showColumnChooser"
                        :allowReordering="gadgetSetting.report.allowReordering"
                        :allowSorting="gadgetSetting.report.allowSorting"
                        :load="load"
                        :dataBound="dataBound"
                        :pageSettings="gadgetSetting.report.pageSettings"
                        ref="datagrid"
                        :showColumnMenu='gadgetSetting.report.showColumnMenu'
                        :toolbarClick='toolbarClick'
                        :allowExcelExport='gadgetSetting.report.allowExcelExport'
                        :allowPdfExport='gadgetSetting.report.allowPdfExport'>
                <e-columns>
                  <e-column v-for="(columnItem, index) in Object.keys(comDataList[0])"
                            :key="index"
                            :sortComparer='(reference, comparer)=>sortComparer(reference, comparer, columnItem)'
                            :field='columnItem'>
                  </e-column>
                </e-columns>
              </ejs-grid>
              <ejs-pivotview v-show="!showGrid"
                             id="pivotview"
                             :dataSourceSettings="gadgetSetting.pivotTable.dataSourceSettings"
                             :gridSettings="gadgetSetting.pivotTable.gridSettings"
                             :toolbar="gadgetSetting.pivotTable.toolbar"
                             :showToolbar="gadgetSetting.pivotTable.showToolbar"
                             :showFieldList="gadgetSetting.pivotTable.showFieldList"
                             style="height:95vh;flex:1"
                             :allowDrillThrough="gadgetSetting.pivotTable.allowDrillThrough"
                             :showTooltip="gadgetSetting.pivotTable.showTooltip"
                             :allowExcelExport="gadgetSetting.pivotTable.allowExcelExport"
                             :allowConditionalFormatting="gadgetSetting.pivotTable.allowConditionalFormatting"
                             :allowNumberFormatting="gadgetSetting.pivotTable.allowNumberFormatting"
                             :allowPdfExport="gadgetSetting.pivotTable.allowPdfExport"
                             :allowCalculatedField="gadgetSetting.pivotTable.allowCalculatedField"
                             :displayOption="gadgetSetting.pivotTable.displayOption"
                             :chartSettings="gadgetSetting.pivotTable.chartSettings"
                             :enableValueSorting="gadgetSetting.pivotTable.enableValueSorting"
                             :saveReport="saveReport"
                             :loadReport="loadReport"
                             :fetchReport="fetchReport"
                             :renameReport="renameReport"
                             :removeReport="removeReport"
                             :newReport="newReport"
                             :showGroupingBar='true'
                             ref="pivotview">
              </ejs-pivotview>
            </div>
          </el-tab-pane>
          <el-tab-pane label="Fields"
                       name="Fields"
                       v-loading='fields_loading'
                       style="height:90vh;overflow-y: auto;">
            <div class="cardHeader">
              <span class="cardTitle threepoints">Fields in this table</span>
            </div>
            <el-table :data="FieldsList.fieldDescription"
                      header-cell-class-name="header_row_style"
                      class="scroll-css"
                      :height="heightHander"
                      style="width: 100%;flex:none">
              <el-table-column prop="name"
                               style="color:#138DC7"
                               label="Fields name">
                <template slot-scope="scope">
                  <span class="header_name">{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="type"
                               :label="$t('custom.dataset.type')">
              </el-table-column>
              <el-table-column prop="dbType"
                               :label="$t('custom.dataset.dbType')">
              </el-table-column>
              <el-table-column prop="description"
                               :label="$t('custom.dataset.fieldsdescriptionTab')">
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="Linked"
                       class="linked-widgets"
                       v-loading='link_loading' style="height:75vh;overflow-y: auto;">
            <template v-slot:label> {{$t('custom.dataset.linkedbtn')}} <span class="num">({{linkedData.length}})</span></template>
            <div class="cardHeader">
              <span class="cardTitle threepoints">{{$t('custom.dataset.linkedbtnTable')}}</span>
            </div>
            <el-checkbox v-model="checked"
                         @change="requestLinkedList"
                         v-if="$hasPermission('sys:dataset:link:widget:show:all')"
                         style="margin-bottom: 10px;">Show All Widget</el-checkbox>
            <el-table :data="linkedData.slice((LinkcurPage-1)*10,LinkcurPage*10)"
                      header-cell-class-name="header_row_style"
                      style="width: 100%;"
                      height="280" class="link-widget">
              <el-table-column prop="name"
                               :label="$t('custom.dataset.name')">
                <template slot-scope="scope">
                  <span class="header_name">{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="reportName"
                               :label="$t('custom.dataset.linkreport')">
              </el-table-column> -->
              <el-table-column prop="reportNum"
                               :label="$t('custom.dataset.linkreport')">
                <template slot-scope="scope">
                  <el-button type="text"
                             size="mini"
                             @click="showLinkedDialog(scope.row)">{{scope.row.reportNum}}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="businessType"
                               :label="$t('custom.dataset.businessType')">
              </el-table-column>
              <el-table-column prop="status"
                               :label="$t('custom.dataset.status')">
              </el-table-column>
              <el-table-column prop="reuse"
                               :label="$t('custom.dataset.reuse')">
                <template slot-scope="scope">
                  <span>{{boolTextFormat(scope.row.reuse)}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="updateDate"
                               :label="$t('custom.dataset.updateDate')">
                <template slot-scope="scope">
                  <span>{{timeFormat(scope.row.updateDate)}}</span>
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <el-button type="success"
                             size="mini"
                             v-if="scope.row.tenantCode === $store.state.user.tenantCode||scope.row.tenantCode==='1001'"
                             @click="widgetDesign(scope.row)">{{$t('custom.widget.designbtn')}}</el-button>
                  <!-- <el-button type="danger" size="mini" v-if="hasdeletePermission(scope.row)" @click="widgetDelete(scope.row)">Delete</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <div class="link_footer">
              <span>{{ `${otherWidgetCount} widgets from other tenants are also using.` }}</span>
              <el-pagination class="list-page"
                           background
                           :page-size="10"
                           :current-page="LinkcurPage"
                           layout="prev, pager, next"
                           @current-change="handleCurrentChange"
                           :total="linkedData.length">
            </el-pagination>
            </div>   
            <model :showSetting="queryModelDefaultSetting.showSetting"
                   @queryModelClosed="queryModelClosed"
                   :dataInfo="queryModelDefaultSetting.dataInfo"
                   :mappingForm="mappingFormSetting"
                   :updateGadget="upgradeGadgetSetting" />
          </el-tab-pane>
          <el-tab-pane name="LinkedBot"
                       v-loading='linkBot_loading'
                       style="height:75vh;overflow-y: auto;">
            <template v-slot:label> {{$t('custom.dataset.linkedbotbtn')}} <span class="num">({{linkedBotData.length}})</span></template>

            <div class="cardHeader">
              <span class="cardTitle threepoints">{{$t('custom.dataset.linkedbotbtnTable')}}</span>
            </div>
            <el-checkbox v-model="checkedBot"
                         v-if="$hasPermission('sys:dataset:linkedbot')"
                         @change="requestLinkedBotList"
                         style="margin-bottom: 10px;">Show All Tenant</el-checkbox>
            <el-table :data="linkedBotData.slice((LinkBotcurPage-1)*10,LinkBotcurPage*10)"
                      header-cell-class-name="header_row_style"
                      style="width: 100%"
                      height="280" class="link-bot">
              <el-table-column prop="name"
                               :label="$t('custom.dataset.name')">
                <template slot-scope="scope">
                  <span class="header_name">{{scope.row.name}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="description"
                               :label="$t('custom.dataset.fieldsdescriptionTab')">
              </el-table-column>
              <el-table-column prop="enable"
                               :label="$t('custom.bots.trigger')">
                <template slot-scope="scope">
                  <span>{{boolTextFormat(scope.row.enable)}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="alert"
                               :label="$t('custom.bots.alert')">
                <template slot-scope="scope">
                  <span>{{boolTextFormat(scope.row.alert)}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="updateTime"
                               :label="$t('custom.dataset.updateDate')">
                <template slot-scope="scope">
                  <span>{{timeFormat(scope.row.updateTime)}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="tenantCode"
                               v-if="checkedBot"
                               label="Client Code">
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <el-button type="success"
                             size="mini"
                             @click="botView(scope.row)">View</el-button>
                  <!-- <el-button type="danger" size="mini" v-if="$hasPermission('sys:bots:delete')" @click="botDelete(scope.row)">Delete</el-button> -->
                </template>
              </el-table-column>
            </el-table>
            <el-pagination class="list-page"
                           background
                           :page-size="10"
                           :current-page="LinkBotcurPage"
                           layout="prev, pager, next"
                           @current-change="handleBotCurrentChange"
                           :total="linkedBotData.length">
            </el-pagination>

          </el-tab-pane>
          <el-tab-pane label="Logs"
                       name="Logs"
                       style="height:75vh;overflow-y: auto;"
                       v-if="$hasPermission('sys:dataset:tab:logs')">
            <div class="cardHeader">
              <span class="cardTitle threepoints">Recent Update history</span>
            </div>
            <div v-loading="logsListLoading">
              <el-table :data="datasetLogList"
                        class="data-table-css screen-y scroll-css"
                        style="width:55%;height:50vh;font-size: 14px;"
                        height="280">
                <el-table-column prop="createDate"
                                 label="Last Updated Time"
                                 align="left">
                  <template slot-scope="scope">
                    {{ scope.row.createDate | ClientFormatTimer }}
                  </template>
                </el-table-column>
                <el-table-column prop="creatorName"
                                 label="Updated By"
                                 align="left">
                </el-table-column>
                <el-table-column align="left">
                  <template slot-scope="scope">
                    <el-button type="success"
                               size="mini"
                               @click="logInfoView(scope.row)">Detail</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination class="list-page"
                             layout="prev, pager, next"
                             background
                             style="width: 55%;"
                             hide-on-single-page
                             :total="datasetLogListPageInfo.total"
                             :page-size="datasetLogListPageInfo.size"
                             :page-count='5'
                             :current-page='datasetLogListPageInfo.current'
                             @current-change="handleDatasetLogCurrentChange">
              </el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <linked-widget v-if="linkWidgetVisible"
                   ref="linkWidget"
                   @refreshDataList="cardQuery"></linked-widget>
    <add-or-update v-if="addOrUpdateVisible"
                   @refreshData="requestFieldsList"
                   ref="addOrUpdate"></add-or-update>
    <el-dialog :visible.sync="showLogInfo"
               width="45%"
               :destroy-on-close="true"
               title="Updated Info"
               append-to-body>
      <v-jsoneditor v-model="datasetLogInfo"
                    :options="jsoneditorSetting.options"
                    :plus="jsoneditorSetting.plus"
                    :height="jsoneditorSetting.height"
                    :indentation="jsoneditorSetting.indentation"
                    :search="jsoneditorSetting.search"
                    :path="jsoneditorSetting.path"
                    :color="jsoneditorSetting.color"
                    @error="onError"></v-jsoneditor>
    </el-dialog>

    <el-dialog :visible="!!recentDialogType"
               width="420px"
               custom-class="sync-dataset-dialog dialog__header--shadow"
               @close="handleCloseRecentDialog"
               @closed="handleClosedRecentDialog">
      <template v-slot:title>
        <span class="sync-dataset-dialog--title">{{$t('statement.sd')}}</span>
      </template>
      <SyncDatasetViewForm v-if="recentDialogType === 'view'"
                           :data="selectedRecentHistoryRow"
                           :params="FieldsList" />
      <SyncDatasetStartForm v-if="recentDialogType === 'start'"
                            :params="FieldsList"
                            @event:end="handleEnd" />
    </el-dialog>
  </el-card>
  <div class="absolute inset-0 flex flex-col"
       v-loading="authLoading"
       v-else>
    <ZContainer>
      <ZEmpty description="No Permission"
              v-if="!authLoading" />
    </ZContainer>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'

import { getUrlQureyParams, currentTabRemoveHandle, GlobalTimeformat } from '@/utils/common'
import { isNumber } from '@/utils/validate'
import model from '@/components/gadget/query-model/query-model.vue'
import AddOrUpdate from './add-or-update'
import { LinkComponent } from './components/LinkComponent.js'
import moment from 'moment'
import TypeFilter from '@/components/script-render/components/type-filter'
import { filterJson } from '@/components/dashboard-filter/filter-json'
import LinkedWidget from './linked-widget'
import SyncDatasetViewForm from './components/sync-dataset-view-form'
import SyncDatasetStartForm from './components/sync-dataset-start-form'
import axios from 'axios'
import BCreateWidget from '@/components/storybook/b-create-widget/index'
import ZContainer from '@/components/storybook/z-container'
import ZEmpty from '@/components/storybook/z-empty'
import { deleteBotInfoApi,fetchLinkedWidgets,deleteLinkedWidget } from '@/api/new'

export default {
  mixins: [mixinGadgetViewModule],
  components: {
    ZContainer,
    ZEmpty,
    model,
    AddOrUpdate,
    LinkComponent,
    TypeFilter,
    LinkedWidget,

    SyncDatasetViewForm,
    SyncDatasetStartForm,
    BCreateWidget
  },
  data () {
    return {
      selectedRecentHistoryRow: undefined,
      recentDialogType: undefined,

      saveDatasetFilterLoading: false,
      dialogVisible: false,
      sortByOptions: [
        { label: 'aaa', value: 'aaa' },
        { label: 'bbb', value: 'bbb' },
        { label: 'ccc', value: 'ccc' },
        { label: 'ddd', value: 'ddd' }
      ],
      link_loading: false,
      fields_loading: false,
      LinkcurPage: 1,
      checked: false,
      showGrid: true,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {}
        }
      },
      linkedData: [],
      otherWidgetCount: 0,
      FieldsList: {},
      activeName: 'datasets',
      isGridInit: false,
      dataList: [],
      loading: false,
      gadgetHeight: window.innerHeight,
      heightoffset: 60,
      noDataImageUrl: this.$ossLink + '/app/gadget/gadget_no_data.jpg',
      gadgetSetting: {
        headerTitle: '',
        headerDescription: '',
        report: {
          showColumnMenu: true,
          allowResizing: true,
          allowFiltering: true,
          filterSettings: { type: 'Excel' },
          allowGrouping: true,
          allowPaging: true,
          allowExcelExport: true,
          allowPdfExport: true,
          toolbar: ['PdfExport', 'CsvExport', 'ColumnChooser'],
          showColumnChooser: true,
          groupOptions: {},
          allowReordering: true,
          allowSorting: true,
          allowTextWrap: true,
          height: window.innerHeight - 230,
          pageSettings: { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000], pageCount: 4 },
          groupSettings: {
            allowReordering: false,
            columns: [],
            disablePageWiseAggregates: false,
            enableLazyLoading: false,
            showDropArea: true,
            showGroupedColumn: false,
            showToggleButton: false
          }
        },
        pivotTable: {
          dataSourceSettings: {
            dataSource: this.comDataList
          },
          showTooltip: false,
          enableValueSorting: true,
          gridSettings: { columnWidth: 140 },
          width: '100%',
          allowDrillThrough: true,
          allowExcelExport: true,
          allowConditionalFormatting: true,
          allowNumberFormatting: true,
          allowPdfExport: true,
          showToolbar: true,
          allowCalculatedField: true,
          showFieldList: true,
          displayOption: { view: 'Both' },
          chartSettings: {
            title: 'Sales Analysis',
            load: (args) => {
              let selectedTheme = location.hash.split('/')[1]
              selectedTheme = selectedTheme || 'Material'
              args.chart.theme = (selectedTheme.charAt(0).toUpperCase() +
                selectedTheme.slice(1))
            }
          },
          toolbar: [
            'New',
            'Save',
            'SaveAs',
            'Rename',
            'Remove',
            'Load',
            'Grid',
            'Chart',
            'Export',
            'SubTotal',
            'GrandTotal',
            'Formatting',
            'FieldList'
          ],
          hyperlinkSettings: {
            cssClass: 'e-custom-class',
            showHyperlink: true,
            showRowHeaderHyperlink: false,
            showColumnHeaderHyperlink: false,
            showValueCellHyperlink: false,
            showSummaryCellHyperlink: false,
            headerText: undefined,
            conditionalSettings: [{
              measure: 'mrPercent',
              conditions: 'NotBetween',
              value1: 0,
              value2: 0
            },
            {
              measure: 'atPercent',
              conditions: 'NotBetween',
              value1: 0,
              value2: 0
            }
            ]
          }
        }
      },
      addOrUpdateVisible: false,
      checkedBot: false,
      LinkBotcurPage: 1,
      linkBot_loading: false,
      linkedBotData: [],
      useLayerStatus: true,
      datasetLayerSelectLoading: false,
      layerList: [],
      datasetLayerId: null,
      dataClearningList: [],
      dataClearningListPageInfo: {
        total: 0,
        current: 1,
        size: 20
      },
      dataLogListLoading: false,
      logsListLoading: false,
      datasetLogList: [],
      datasetLogListPageInfo: {
        total: 0,
        current: 1,
        size: 10
      },
      showLogInfo: false,
      jsoneditorSetting: {
        options: { mode: 'tree', modes: ['tree', 'code'] },
        plus: false,
        height: '400px',
        indentation: 2,
        search: true,
        color: 'red',
        path: false
      },
      datasetLogInfo: null,
      syncLoading: false,
      timers: null,
      rowLimitType: 2,
      rowLimit: '100',
      dataSort: {
        rowLimit: '100',
        orderFields: '',
        orderBy: ''
      },
      filterSetting: {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      },
      linkWidgetVisible: false,
      lastUpdateTime: '',

      logLoading: false,
      logList: [],

      permission: false,
      authLoading: false,
      clearloading: false,
      saveloading: false
    }
  },

  async created () {
    Vue['_this_dataset_view'] = this
    let datasetId = getUrlQureyParams('pageid')
    let localLayerId = JSON.parse(localStorage.getItem('dataset-view-' + `${datasetId}`))
    if (localLayerId) {
      this.useLayerStatus = !this.useLayerStatus
      this.datasetLayerId = localLayerId
    }
    try {
      this.authLoading = true
      await this.getDashboardAuth()
      this.requestFieldsList()
      this.query()

      this.requestLinkedList()
      this.requestLinkedBotList()

    } catch (error) {

    } finally {
      this.authLoading = false
    }
  },

  filters: {
    filterType (value) {
      return value ? 'Sync' : 'Cleaning'
    }

  },
  beforeDestroy () {
    clearInterval(this.timers)
  },
  computed: {
    heightHander () {
      return document.body.offsetHeight - 300
    },
    comDataList () {
      var _self = this
      var retdata = _self.dataList
      return retdata
    },
    layerTempList () {
      try {
        let datasetId = getUrlQureyParams('pageid')
        if (datasetId) {
          return this.layerList//  this._.filter(this.layerList, { 'datasetId': datasetId })
        }
      } catch (error) {
        return []
      }
    },
    isShowSync () {
      let temp = false
      if (this.FieldsList.id && this.FieldsList.refreshType === 'javaapi' && this.FieldsList.apiList.length > 0) {
        temp = true
      }
      return temp
    }
  },
  watch: {
    activeName (newVal, oldVal) {
      if (oldVal === 'Detail') {
        if (window.getDataClearningLogApi) window.getDataClearningLogApi()
      }
      if (newVal === 'Detail') {
        this.getDataClearningList()
      }
    }
  },
  methods: {
    sortComparer (reference, comparer, columnItem) {
      const curItem=Array.isArray(this.FieldsList.fieldDescription)&&this.FieldsList.fieldDescription.find(v=>v.name===columnItem)
      if(curItem&&curItem.dbType==='number'){
        reference=BigInt(reference||0)
        comparer=BigInt(comparer||0)
      }
      if (reference < comparer) {
        return -1;
      }
      if (reference > comparer) {
        return 1;
      }
      return 0;
    },
    async getDashboardAuth () {
      const { getAssert } = this.$interface.system
      const { pageid } = this.$route.query
      const params = {
        sourceId: pageid,
        sourceType: 5
      }
      const { data: response } = await getAssert(params)
      if (response.code === 403) {
        // eslint-disable-next-line no-throw-literal
        throw 'no permission'
      }
      this.permission = true
    },
    async getSyncLogList () {
      const { get } = this._
      const { syncLog } = this.$interface.reports
      try {
        this.logLoading = true

        const { id } = this.FieldsList
        const params = {
          id
        }
        let { data: response } = await syncLog(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.logList = get(response, 'data', [])
      } catch (error) {

      } finally {
        this.logLoading = false
      }
    },

    async getLastUpdateTime () {
      const { get } = this._
      const { lastUpdateTime } = this.$interface.reports
      try {
        const params = {
          id: this.FieldsList.id
        }
        let { data: response } = await lastUpdateTime(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.lastUpdateTime = get(response, 'data.createTime')
      } catch (error) {

      } finally {

      }
    },

    handleOpenRecentDialog (type, row) {
      this.recentDialogType = type
      if (row) {
        this.selectedRecentHistoryRow = row
      }
    },
    handleCloseRecentDialog () {
      this.recentDialogType = undefined
    },
    handleClosedRecentDialog () {
      this.selectedRecentHistoryRow = undefined
    },

    showLinkedDialog (row) {
      this.linkWidgetVisible = true
      this.$nextTick(() => {
        // this.$refs['linkWidget'].showDelete = showDelete
        this.$refs['linkWidget'].dataForm.gadgetId = row.gadgetId
        // this.$refs['linkWidget'].deleteData.id = deleteDataId
        this.$refs['linkWidget'].init()
      })
    },
    openFilterDialog () {
      // if (this.FieldsList.dataFilter) {
      //   this.filterSetting.dataForm = JSON.parse(JSON.stringify(this.FieldsList.dataFilter))
      // }
      this.dialogVisible = true
    },
    showDataSortDialog () {
      if (this.FieldsList.dataSort) {
        this.dataSort = JSON.parse(JSON.stringify(this.FieldsList.dataSort))
      }
      if (!this.dataSort.orderFields) {
        this.dataSort.orderFields = this.filterSetting.scriptItem[this.filterSetting.scriptItem.keyOptions][0].value
      }
      // if (this.rowLimit) {
      //   this.rowLimitType = 2
      // } else {
      //   this.rowLimitType = 1
      // }
    },
    saveFilters (dataFrom) {
      if (this.$refs.typeFilter.checkdataArr()) {
        this.saveDatasetFilter(this.FieldsList.id, dataFrom).then(() => {
          this.dialogVisible = false
          this.requestFieldsList()
          this.query("dataFilter")
        })
      }
    },
    saveDatasetFilter (id, dataFilter) {
      this.saveDatasetFilterLoading = true
      return this.$interface.reports.putDatasetFilterApi(id, { dataFilter }).then(({ data: res }) => {
        this.saveDatasetFilterLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$message.success(this.$t('prompt.success'))
      }).catch(() => {
        this.saveDatasetFilterLoading = false
      })
    },
    saveDatasetSort (id, dataSort) {
      this.saveDatasetFilterLoading = true
      return this.$interface.reports.putDatasetSortApi(id, { dataSort }).then(({ data: res }) => {
        this.saveDatasetFilterLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$message.success(this.$t('prompt.success'))
      }).catch(() => {
        this.saveDatasetFilterLoading = false
      })
    },
    handleClose (done) {
      this.filterIndex = -1
      this.filterSetting = {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      }
      this.dialogVisible = false
      this.isSave = false
    },
    manuallySync () {
      //
      this.syncLoading = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        id: this.FieldsList.id,
        type: 'dataset'
      }
      this.$interface.apiManager.getSyncStartApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data && res.data.length > 0) {
          this.syncResult(params, res.data)
        }
      }).catch(() => {
        this.syncLoading = false
      })
    },
    syncResult (data, resultList) {
      const params = {
        ...data
      }
      this.$interface.apiManager.getSyncResultApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let successNum = 0
        if (res.data && res.data.length > 0) {
          for (let index = 0; index < resultList.length; index++) {
            const elementResult = resultList[index]
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i]
              if (elementResult.data && element.data && elementResult.data.action === element.data.action) {
                clearInterval(this.timers)
                if (moment(elementResult.data.time).isBefore(element.data.time)) {
                  if (element.data.status === 'OK') {
                    successNum++
                  }
                } else {
                  this.syncStart(data, resultList)
                }
              }
            }
          }
          if (successNum === resultList.length) {
            this.syncLoading = false
            clearInterval(this.timers)
            return this.$message.success('Sync Success')
          }
        } else {
          this.syncStart(data, resultList)
        }
      }).catch(() => {
        this.syncLoading = false
      })
    },
    syncStart (data, resultList) {
      clearInterval(this.timers)
      this.timers = setInterval(() => {
        this.syncResult(data, resultList)
      }, 5000)
    },
    handleCurrentChange: function (currentPage) {
      this.LinkcurPage = currentPage
    },
    handleBotCurrentChange: function (currentPage) {
      this.LinkBotcurPage = currentPage
    },

    handleEnd () {
      this.getSyncLogList()
      this.getLastUpdateTime()
    },
    handleLogCurrentChange: function (currentPage) {
      this.dataClearningListPageInfo.current = currentPage
      this.getDataClearningList()
    },
    getDataClearningList () {
      let CancelToken = axios.CancelToken
      this.dataLogListLoading = true
      let params = {
        sysDatasetId: this.FieldsList.id,
        current: this.dataClearningListPageInfo.current,
        size: this.dataClearningListPageInfo.size,
        desc: 'create_time'
        // startTime: moment().format('YYYY-MM-DD 00:00:00'),
        // endTime: moment().format('YYYY-MM-DD 23:59:00')
      }
      this.$interface.reports.getDataClearningLogApi(params, {
        cancelToken: new CancelToken((c) => {
          window.getDataClearningLogApi = c
        })
      }).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data.records && res.data.records.length > 0) {
          this.dataClearningList = res.data.records
          this.dataClearningListPageInfo.total = res.data.total * 1
          this.dataClearningListPageInfo.currentPage = res.data.current * 1
        }
      }).finally(() => {
        this.dataLogListLoading = false
      })
    },
    logInfoView (data) {
      this.datasetLogInfo = null
      this.datasetLogInfo = JSON.parse(data.requestParams)
      this.showLogInfo = !this.showLogInfo
    },
    onError (value) {

    },
    handleDatasetLogCurrentChange: function (currentPage) {
      this.datasetLogListPageInfo.current = currentPage
      this.getDatasetLogList()
    },
    getDatasetLogList () {
      this.logsListLoading = true
      let params = {
        requestUri: `/sys/dataset/${this.FieldsList.id}/update`,
        page: this.datasetLogListPageInfo.current,
        limit: this.datasetLogListPageInfo.size,
        order: 'desc',
        orderField: 'create_date'
      }
      this.$interface.system.getLogOperationListApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data.list && res.data.list.length > 0) {
          this.datasetLogList = res.data.list
          this.datasetLogListPageInfo.total = res.data.total * 1
          this.datasetLogListPageInfo.currentPage = res.data.page * 1
        }
        this.logsListLoading = false
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    upgradeGadgetSetting () { },
    mappingFormSetting (to, from) { },
    widgetDesign (e) {
      this.queryModelDefaultSetting.dataInfo.businessId = e.businessId
      this.queryModelDefaultSetting.dataInfo.gadgetId = e.gadgetId
      this.queryModelDefaultSetting.dataInfo.gadgetType = e.gadgetType
      this.queryModelDefaultSetting.dataInfo.gadgetSetting = e.gadgetSetting
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    handleClick (tab, event) {

    },
    requestFieldsList () {
      if(!this.$route.query.pageid) return
      this.fields_loading = true
      this.$interface.reports.getReportDatasetInfoApi(this.$route.query.pageid)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.fields_loading = false
            return this.$message.error(res.msg)
          }
          if (res.data && !res.data.isPermission && res.data.isPermission !== undefined) {
            this.$router.replace({ name: '404' })
            return
          }
          this.FieldsList = res.data
          try {
            if(res.data.dataSort) {
              this.dataSort = JSON.parse(JSON.stringify(res.data.dataSort)) || {}
            }

          } catch (error) {
            this.dataSort = {}
          }
          // LinkComponent.$on(`refreshData-${this.FieldsList.id}`, () => {
          //   this.requestFieldsList()
          // })
          this.getLayerList()
          var arr = []
          JSON.parse(JSON.stringify(res.data.fieldDescription)).forEach(item => {
            var obj = {
              label: item.name,
              value: item.name,
              type: item.type
            }
            arr.push(obj)
          })
          this.filterSetting.scriptItem[this.filterSetting.scriptItem.keyOptions] = arr
          this.getDataClearningList()
          this.getDatasetLogList()
          this.getLastUpdateTime()
          this.getSyncLogList()
          this.fields_loading = false
        
        })
        .catch(() => { this.fields_loading = false })
    },
    requestLinkedList () {
      this.link_loading = true
      const params = {
        sysDatasetId: this.$route.query.pageid,
        reuse: true
      }
      if (this.checked) {
        delete params.reuse
      }
      fetchLinkedWidgets(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.link_loading = false
          return this.$message.error(res.msg)
        }
        this.link_loading = false
        this.linkedData = res.data.sysModels || []
        this.otherWidgetCount = res.data.count || 0
      }).catch(() => { this.link_loading = false })
    },
    boolTextFormat (data) {
      if (data === true) {
        return 'True'
      } else {
        return 'False'
      }
    },
    requestLinkedBotList () {
      this.linkBot_loading = true
      const params = {
        dataSourceId: this.$route.query.pageid
      }
      if (this.checkedBot) {
        params.showAllTenant = true
      }
      this.$interface.bots.getBotByDatasetListApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.linkedBotData = res.data
        this.linkBot_loading = false
      })
    },
    botView (data) {
      this.$store.commit('RECORDBOTID', data.id)
      // this.$router.push({ name: 'mspbots-bots-bak-bot-view-index', query: { botId: data.id } })
      // this.$router.push({ name: 'mspbots-bots-bak-bot-design-index', query: { botId: data.id } })
      this.$router.push({ path: `bot-${data.id}`, query: { pageid: 'botdetail', botId: data.id, name: data.name } })
    },
    botDelete (data) {
      this.linkBot_loading = true
      const params = {
        id: data.id
      }
      deleteBotInfoApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.linkBot_loading = false
          return this.$message.error(res.msg)
        }
        this.requestLinkedBotList()
        this.$message.success(res.msg)
        this.linkBot_loading = false
      })
    },
    timeFormat (date) {
      return GlobalTimeformat(date)
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        let columnsList = []
        columnsList = Object.keys(this.dataList[0])
        this.$refs.datagrid.autoFitColumns(columnsList)
        // this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
      }
      this.$refs.datagrid.autoFitColumns()
      // this.loading = false
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = 20 * 20 - 15
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          (this.$refs['datagrid']).pdfExport()
          break
        case 'Excel Export':
          (this.$refs['datagrid']).excelExport()
          break
        case 'CSV Export':
          (this.$refs['datagrid']).csvExport()
          break
      }
    },
    handleClearSort () {
      this.clearloading = true;
      this.dataSort = {
        rowLimit: '100',
        orderFields: '',
        orderBy: ''
      }
      this.changeLimit(this.dataSort, 'clear')
    },
    changeLimit (dataSort, name) {
      if (dataSort.orderBy !== '' && !dataSort.orderFields) {
        return this.$message.error('please select order fields')
      }
      if (name === 'save') this.saveloading = true
      // this.saveDatasetSort(this.FieldsList.id, dataSort).then(() => {
      this.clearloading = false;
      this.saveloading = false;
      this.$refs.sortPopver && this.$refs.sortPopver.doClose()
      this.requestFieldsList()
      this.query()
      this.load()
      this.$refs.datagrid.refresh()
      // })
    },
    // toolbar function
    saveReport: function (args) {
      let reports = []
      let isSaved = false
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        reports = JSON.parse(localStorage[this.$route.query.pageid])
      }
      if (args.report && args.reportName && args.reportName !== '') {
        reports.map(function (item) {
          if (args.reportName === item.reportName) {
            item.report = args.report
            isSaved = true
          }
        })
        if (!isSaved) {
          reports.push(args)
        }
        localStorage[this.$route.query.pageid] = JSON.stringify(reports)
      }
    },
    fetchReport: function (args) {
      let reportCollection = []
      let reeportList = []
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        reportCollection = JSON.parse(localStorage[this.$route.query.pageid])
      }
      reportCollection.map(function (item) {
        reeportList.push(item.reportName)
      })
      args.reportName = reeportList
    },
    loadReport: function (args) {
      let pivotObj = this.$refs.pivotview.ej2Instances
      let reportCollection = []
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        reportCollection = JSON.parse(localStorage[this.$route.query.pageid])
      }
      reportCollection.map(function (item) {
        if (args.reportName === item.reportName) {
          args.report = item.report
        }
      })
      if (args.report) {
        pivotObj.dataSourceSettings = JSON.parse(args.report).dataSourceSettings
      }
    },
    removeReport: function (args) {
      let reportCollection = []
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        reportCollection = JSON.parse(localStorage[this.$route.query.pageid])
      }
      for (let i = 0; i < reportCollection.length; i++) {
        if (reportCollection[i].reportName === args.reportName) {
          reportCollection.splice(i, 1)
        }
      }
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        localStorage[this.$route.query.pageid] = JSON.stringify(reportCollection)
      }
    },
    renameReport: function (args) {
      let reportCollection = []
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        reportCollection = JSON.parse(localStorage[this.$route.query.pageid])
      }
      reportCollection.map(function (item) {
        if (args.reportName === item.reportName) {
          item.reportName = args.rename
        }
      })
      if (
        localStorage[this.$route.query.pageid] &&
        localStorage[this.$route.query.pageid] !== ''
      ) {
        localStorage[this.$route.query.pageid] = JSON.stringify(reportCollection)
      }
    },
    newReport: function () {
      let pivotGridObj = this.$refs.pivotview.ej2Instances
      pivotGridObj.setProperties(
        {
          dataSourceSettings: {
            columns: [],
            rows: [],
            values: [],
            filters: []
          }
        },
        false
      )
    },
    editDataset () {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs['addOrUpdate'].dataForm.id = this.FieldsList.id
        this.$refs['addOrUpdate'].init(this.FieldsList.language === 'sqlagent')
      })
    },
    widgetDelete (data) {
      if (data.reuse === true) {
        return this.$message.error("Can't delete active widget!")
      }
      const params = {
        sysModelId: data.id,
        reportId: data.reportId ? data.reportId : null,
        dashboardId: data.dashboardId ? data.dashboardId : null
      }
      deleteLinkedWidget(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.requestLinkedList()
        this.$message.success(res.msg)
      })
    },
    deleteDataset () {
      if (this.linkedData && this.linkedData.length > 0) {
        return this.$message.warning('This deleted behavior may affect the linked widgets or bots. Are you sure to delete this dataset?')
      }
      if (this.linkedBotData && this.linkedBotData.length > 0) {
        return this.$message.warning('This deleted behavior may affect the linked widgets or bots. Are you sure to delete this dataset?')
      }
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const params = {
          id: this.FieldsList.id
        }
        this.$interface.reports.delReportDatasetApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          currentTabRemoveHandle(this.$store.state.contentTabsActiveName)
          let path = window.location.pathname
          this.$store.state.app.contentIsNeedRefreshCache = true
          if (path === '/Datasets') {
            LinkComponent.$emit('initPageList')
          } else if (path.includes('/InternalDataset')) {
            LinkComponent.$emit('initInteraPageList')
          } else {
            LinkComponent.$emit('initSystemPageList')
          }
          return this.$message.success(res.msg)
        })
      }).catch(() => {
      })
    },
    changeRowLimit () {
      if (!isNumber(this.rowLimit)) {
        return this.$message.error('please enter Number')
      }
      if (!this.rowLimit) {
        return this.$message.error('Please enter limit count')
      }
      if (Number(this.rowLimit) > 2001) {
        return this.$message.error('Up to 2000 pieces of data can be queried')
      }
      // this.query()
      // this.load()
      // this.$refs.datagrid.refresh()
      // this.$refs.sortPopver && this.$refs.sortPopver.doClose()
    },
    blurRowLimit (dataSort) {
      if (this.rowLimitType === 2) {
        if (!isNumber(this.dataSort.rowLimit)) {
          return this.$message.error('please enter Number')
        }
        if (!this.dataSort.rowLimit) {
          return this.$message.error('Please enter limit count')
        }
      } else {
        dataSort.rowLimit = ''
      }
      dataSort.rowLimit = '100'
      this.saveDatasetSort(this.FieldsList.id, dataSort).then(() => {
        this.$refs.sortPopver && this.$refs.sortPopver.doClose()
        this.requestFieldsList()
        this.query()
        this.load()
        this.$refs.datagrid.refresh()
      })
    },
    query (dataFilter) {
      let datasetId = getUrlQureyParams('pageid')
      if (!datasetId)   return   
      this.loading = true
      var _self = this
      let requestParams = ''
      if (this.rowLimitType === 1) {
        requestParams = ''
      } else {
        if (dataFilter === 'dataFilter') {
          requestParams = `filter=limit ${this.rowLimit}&orderBy=${this.dataSort.orderBy}&orderFields=${this.dataSort.orderFields}&dataFilter=true`
        } else {
          requestParams = `filter=limit ${this.rowLimit}&orderBy=${this.dataSort.orderBy}&orderFields=${this.dataSort.orderFields}&dataFilter=flase`
        }

      }
      if (this.datasetLayerId) {
        requestParams += `&datasetLayerId=` + this.datasetLayerId
        localStorage.setItem('dataset-view-' + `${datasetId}`, JSON.stringify(this.datasetLayerId))
      }
      this.$interface.reports.getReportDatasetDataApi(datasetId, requestParams)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          let pivotObj = _self.$refs.pivotview.ej2Instances
          _self.heightoffset = 5
          _self.gadgetHeight = 20 * _self.heightoffset - 15
          // process data
          if (Array.isArray(res.data)) {
            _self.dataList = []
            _self.dataList = res.data
            pivotObj.dataSourceSettings.dataSource = _self.dataList
          }
          _self.isGridInit = false
          // pivotObj.pivotRefresh()
          this.loading = false
        })
        .catch((e) => {
          this.loading = false
          if (e) {
            if (e.response.status === 404) {
            } else if (e.response.status === 500) {
              return this.$message.error('Error, Please try again!')
            } else {
              return this.$message.error(e.response.data.data.message)
            }
          } else {
            return this.$message.error('Error, Please try again!')
          }
        })
    },
    changeLayerStatus () {
      this.useLayerStatus = !this.useLayerStatus
    },
    onLayerChange () {
      let datasetId = getUrlQureyParams('pageid')
      if (!this.datasetLayerId) {
        this.useLayerStatus = true
        this.datasetLayerId = null
        localStorage.setItem('dataset-view-' + `${datasetId}`, JSON.stringify(this.datasetLayerId))
      }
      this.query()
      this.load()
      this.$refs.datagrid.refresh()
    },
    getLayerList () {
      this.datasetLayerSelectLoading = true
      const params = {
        datasetId: this.FieldsList.id
      }
      this.$interface.reports.getDatasetLayerList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.layerList = res.data
        this.datasetLayerSelectLoading = false
        this.$forceUpdate()
      }).catch(() => { this.datasetLayerSelectLoading = false })
    },
    hasEditPermission (data, type) {
      try {
        if (data.language === 'sqlagent') {
          if (!this.$hasPermission('sys:dataset:sourcetype:sqlagent')) {
            return false
          }
        }
        let reportadmin = this.$hasPermission(`sys:${type}:${type}admin`) ? 1 : 0
        let editAuth = this.$hasPermission(`sys:${type}:edit`) ? 1 : 0
        let isCustom = data.businessType === 'Custom' ? 1 : 0
        if (reportadmin + editAuth + isCustom >= 2) {
          return true
        } else {
          return false
        }
      } catch (error) {

      }
    },
    hasDeletePermission (data, type) {
      try {
        if (data.language === 'sqlagent') {
          if (!this.$hasPermission('sys:dataset:sourcetype:sqlagent')) {
            return false
          }
        }
        let reportadmin = this.$hasPermission(`sys:${type}:${type}admin`) ? 1 : 0
        let deleteAuth = this.$hasPermission(`sys:${type}:delete`) ? 1 : 0
        let isCustom = data.businessType === 'Custom' ? 1 : 0
        if (reportadmin + deleteAuth + isCustom >= 2) {
          return true
        } else {
          return false
        }
      } catch (error) {

      }
    }
  },
  deactivated () {
    if (window.getDataClearningLogApi) window.getDataClearningLogApi()
  },
  destroyed () {
    // LinkComponent.$off(`refreshData-${this.FieldsList.id}`)
    delete Vue['_this_dataset_view']
    if (window.getDataClearningLogApi) window.getDataClearningLogApi()
  }

}
</script>

<style scoped lang="scss">
.link_footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
::v-deep .el-table::before {
  height: 0;
}
.recent-dialog {
  .field-item {
    font-size: 14px;

    line-height: 20px;

    .field-item-label {
      font-weight: 600;
      color: rgba(0, 0, 0, 0.5);
    }
    .field-item-content {
      color: rgba(0, 0, 0, 0.75);
    }
  }

  &-fix {
    margin-left: 32px;
    margin-top: 10px;
  }

  &-message {
    color: #404040;
    padding: 8px;
    margin-top: 16px;
    &--success {
      background-color: #eef5dc;
      .recent-dialog-message--icon {
        color: #67c23a;
      }
    }
    &--failed {
      background-color: #fff1f0;
      .recent-dialog-message--icon {
        color: #b11b0d;
      }
    }
    &-content {
      table-layout: fixed;
      word-break: break-all;
      overflow: hidden;
    }
    &--icon {
      margin-right: 8px;
      margin-top: 1px;
    }
  }
}

.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}
.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  padding-left: 0;
  margin-bottom: 12px;
  // border-bottom: 1px solid #eee;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.el-input-group__append,
.el-input-group__prepend {
  color: #138dc7;
}
.el-input__inner {
  width: 130px !important;
}
.showing-text:hover {
  overflow: visible;
}
/* .el-input-group__prepend{
  color: #138DC7;
}
.el-input-group__append{
  color: #138DC7;
} */
.content-wrapper {
  .dataset_detail {
    p {
      font-size: 14px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.5);
      line-height: 20px;
      margin: 5px 0;
    }
    div {
      font-size: 16px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.75);
      line-height: 22px;
      margin-bottom: 20px;
    }
  }
  .header_name {
    font-size: 14px;
    font-weight: 500;
    color: #138dc7;
  }
  ::v-deep .header_row_style {
    background: #f0f0f0 !important;
    border-radius: 2px 0px 0px 0px;
  }
}
.aui-card--fill {
  height: calc(calc(100vh - 50px - 70px));
  ::v-deep .e-grid .e-content {
    height: calc(calc(100vh - 100px - 290px - 110px)) !important;
  }
}
.linked-widgets {
  display: flex;
  flex-direction: column;
}

.num {
  color: #138dc7;
}
::v-deep .link-widget .el-table__body-wrapper {
  height: calc(100vh - 520px);
  max-height: calc(100vh - 520px);
  overflow-y: auto;
}
::v-deep .link-bot .el-table__body-wrapper {
  height: calc(100vh - 520px);
  max-height: calc(100vh - 520px);
  overflow-y: auto;
}
</style>
<style lang="scss">
@import "./components/sync-dataset.scss";
.datset_filter.el-popover {
  padding: 0;
}
.datasetview {
  & > .el-card__body {
    position: relative;
    // display: flex;
    flex-direction: column;
    & > .control-section {
      flex: 1;
      display: flex;
      flex-direction: column;
      & > .content-wrapper {
        flex: 1;
        display: flex;
        flex-direction: column;
        & > .el-tabs {
          flex: 1;
          display: flex;
          flex-direction: column;
          & > .el-tabs__content {
            flex: 1;
            display: flex;
            flex-direction: column;
            .el-tab-pane {
              flex: 1;
              display: flex;
              flex-direction: column;
              #pivotviewcontainerwrapper {
                flex: 1;
              }
            }
          }
        }
      }
    }
  }

  .e-popup.e-popup-open.e-dialog {
    // display: inline-flex !important;
  }
  .e-grid .e-dialog .e-dlg-content {
    height: 200px !important;
  }
  .e-pivotfieldlist-wrapper.e-dialog {
    width: 50% !important;
    height: 90% !important;
  }
  .el-table__header {
    font-size: 14px;
  }
  .el-table__header thead th {
    background-color: #f8f8f8;
    padding: 9px 0;
  }
  .el-table__body tbody td {
    padding: 4px 0;
  }
  
  .list-page {
    margin-top: 0;
    padding: 9px;
    border-left: 1px solid #f0f0f0;
    border-right: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    background-color: #f8f8f8;
    text-align: right;
    & > button {
      background-color: #fff !important;
    }
  }
  .el-pagination.is-background .el-pager li:not(.disabled) {
    background-color: #fff;
  }
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: $--theme-color;
    color: #fff;
  }
  .el-tag--mini {
    width: 90px;
  }
  .data-table-css {
    border-left: 1px solid #f0f0f0;
    border-right: 1px solid #f0f0f0;
  }
  .el-loading-spinner .circular {
    width: 30px;
    height: 30px;
    margin-top: 5px;
  }
  .default_sort {
    padding: 0 8px;
    text-align: center;
    // width:137px;
    height: 28px;
    line-height: 28px;
    border-radius: 3px;
    &:hover {
      color: $--theme-color;
      background-color: $--theme-color-background;
    }
    span {
      font-size: 14px;
    }
  }
}
.active_from {
  color: $--theme-color;
}
</style>
